﻿// SilverlightDesktop.Net - http://www.SilverlightDesktop.net
// Copyright (c) 2008
// by SilverlightDesktop.Net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Text;
using Microsoft.VisualBasic;
using SilverlightDesktopCore.DAL;

public class Authendication
{
    private int _PortalID;
    private int _UserID;
    private string _Password;
    private int _ModuleId;
    private string _IPAddress;

    public Authendication()
    {
        _PortalID = 0;
        _ModuleId = 0;
        _UserID = -1;
        _Password = "";
        _IPAddress = "127.0.0.1";
    }

    public Authendication(SilverlightDesktopAuthendicationHeader Credentials)
    {
        _PortalID = Credentials.PortalID;
        _ModuleId = Credentials.ModuleId;
        _UserID = Credentials.UserID;
        _Password = Credentials.Password.Trim();
        _IPAddress = Credentials.IPAddress;
    }

    #region SetSilverlightKey
    public static string SetSilverlightKey(int intUserID, string IPAddress)
    {
        string strRandomPassword = "";
        if (intUserID > 0)
        {
            // Get a random password
            Utility Utility = new Utility();
            strRandomPassword = Utility.GetRandomPassword();

            //  Store the encryption key in the users record 

            SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();

            var SilverlightDesktopUser = (from DesktopUser in SilverlightDesktopDAL.SilverlightDesktopUsers
                                          where DesktopUser.UserID == intUserID
                                          select DesktopUser).FirstOrDefault();

            SilverlightDesktopUser.SilverlightPassword = strRandomPassword;
            SilverlightDesktopUser.IPAddress = IPAddress;
            SilverlightDesktopDAL.SubmitChanges();
        }
        return strRandomPassword;
    }

    public string SetSilverlightKey()
    {
        return SetSilverlightKey(_UserID, _IPAddress);
    }
    #endregion

    #region IsUserValid
    public bool IsUserValid()
    {
        if (_UserID == -1)
        {
            return false;
        }

        SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();

        //  Get the SilverlightKey
        var SilverlightUser = (from ASilverlightDesktopUser in SilverlightDesktopDAL.SilverlightDesktopUsers
                              where ASilverlightDesktopUser.UserID == _UserID 
                              select ASilverlightDesktopUser).FirstOrDefault();

        // Don't allow user if user is not active
        if (SilverlightUser.Active == false)
        {
            return false;
        }

        if ((SilverlightUser.SilverlightPassword == _Password) & (Strings.Left(SilverlightUser.IPAddress,6) == Strings.Left(_IPAddress,6)))
        {
            return true;
        }
        else
        {
            if(Strings.Left(SilverlightUser.IPAddress,6) == Strings.Left(_IPAddress,6))
            {
                // The correct IP address was used
                // To prevent a brute force attack scramble the password
                // A hacker is now chasing a moving target
                SetSilverlightKey();
            }
            return false;
        }
    }
    #endregion

    #region IsUserValid(string ModuleName)
    public bool IsUserValid(string ModuleName)
    {
        if (_UserID == -1)
        {
            return false;
        }

        SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();

        var SilverlightModule = (from Module in SilverlightDesktopDAL.SilverlightDesktopModules
                                 where Module.ModuleName.ToLower() == ModuleName.ToLower()
                                 select Module).FirstOrDefault();

        if (SilverlightModule == null)
        {
            return false;
        }

        // Don't allow user if not in the role for the module or a SuperUser
        // or module role set to Any
        UserInfo objUserInfo = GetUserInfo();
        if (
            !objUserInfo.IsInRole(SilverlightModule.Role) &
            SilverlightModule.Role.ToLower() != "any" &
            !objUserInfo.IsSuperUser
            )
        {
            return false;
        }

        // Don't allow user if user is not active
        if (objUserInfo.Active == false)
        {
            return false;
        }

        //  Get the SilverlightKey
        var SilverlightKey = (from ASilverlightDesktopUser in SilverlightDesktopDAL.SilverlightDesktopUsers
                              where ASilverlightDesktopUser.UserID == _UserID
                              select ASilverlightDesktopUser).FirstOrDefault();

        if ((SilverlightKey.SilverlightPassword == _Password) & (Strings.Left(SilverlightKey.IPAddress, 6) == Strings.Left(_IPAddress, 6)))
        {
            return true;
        }
        else
        {
            if (SilverlightKey.IPAddress == _IPAddress)
            {
                // The correct IP address was used
                // To prevent a brute force attack scramble the password
                // A hacker is now chasing a moving target
                SetSilverlightKey();
            }
            return false;
        }
    } 
    #endregion

    #region GetUserInfo
    public UserInfo GetUserInfo()
    {
        return GetUserInfo(_PortalID, _UserID);
    }

    public UserInfo GetUserInfo(int PortalID, int UserID)
    {
        UserInfo UserInfo = new UserInfo();

        if (UserID == -1)
        {
            return UserInfo;
        }

        SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();

        var result = (from ASilverlightDesktopUser in SilverlightDesktopDAL.SilverlightDesktopUsers
                      where ASilverlightDesktopUser.UserID == UserID
                      select ASilverlightDesktopUser).FirstOrDefault();

        UserInfo.DisplayName = result.FirstName + " " + result.LastName;
        UserInfo.Email = result.Email;
        UserInfo.FirstName = result.FirstName;
        UserInfo.IsSuperUser = result.SuperUser;
        UserInfo.LastName = result.LastName;
        UserInfo.PortalID = 0;
        UserInfo.UserID = result.UserID;
        UserInfo.Username = result.UserName;
        UserInfo.Roles = new string[] { result.Role };
        UserInfo.Active = result.Active;

        return UserInfo;
    }
    #endregion

}

